import api from './index'

var storage = require('@system.storage')


export function userLogin(uname, pwd) {
    console.log(uname, pwd)
    return api.login({
        username: uname,
        password: pwd
    }).then((response) => {
        console.log(JSON.stringify(response))
        var value = JSON.parse(response.data)
        if (value.errorCode === -1) {
            Promise.reject(value.errorMsg)
        }
        storage.set({
            key: 'auth',
            value: response.headers['Set-Cookie'],
            success: function (data) {
                console.log('cookies保存成功')
            }
        })
        storage.set({
            key: 'user',
            value: value.data
        })
        storage.set({
            key: 'isLogin',
            value: true
        })
        return Promise.resolve(value.data)
    }).catch((err) => {
        return Promise.reject('登录失败')
    })
}

export function userRegister(uname, pwd, repwd) {
    return api.register({
        username: uname,
        password: pwd,
        repassword: repwd
    }).then((response) => {
        console.log(JSON.stringify(response))
        var value = JSON.parse(response.data)
        if (value.errorCode === -1) {
            Promise.reject(value.errorMsg)
        }
        storage.set({
            key: 'auth',
            value: response.headers['Set-Cookie'],
            success: function (data) {
                console.log('cookies保存成功')
            }
        })
        storage.set({
            key: 'user',
            value: value.data
        })
        storage.set({
            key: 'isLogin',
            value: true
        })
        return Promise.resolve(value.data)
    }).catch((err) => {
        return Promise.reject('注册失败')
    })
}